package com.fengjue.filter;

import com.fengjue.pojo.Menu;
import com.fengjue.pojo.Role;
import com.fengjue.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 根据请求的url去判断角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        // 获取请求的url
        FilterInvocation object1 = (FilterInvocation) object;
        String fullRequestUrl = object1.getFullRequestUrl();
        String requestUrl = object1.getRequestUrl();
        System.out.println("requestUrl = " + requestUrl);
        System.out.println("fullRequestUrl = " + fullRequestUrl);

        // 从数据库通过角色获取菜单权限
        List<Menu> menusWithRole = menuService.getMenusWithRole();
//        System.out.println("menusWithRole = " + menusWithRole);
        // 遍历角色
        for (Menu menu : menusWithRole) {
            // 得到权限url
            String url = menu.getUrl();
            System.out.println("url = " + url);
            // 权限对比
            boolean match = antPathMatcher.match(url, requestUrl);
            System.out.println("requestUrl = " + requestUrl);
            System.out.println("match = " + match);
            // 判断请求url与权限角色是否匹配
            if (match){
                // 返回
                String[] collect =
                        menu.getRoles().stream()
                                .map(Role::getName).toArray(String[]::new);

                return SecurityConfig.createList(collect);
            }else {
                throw new AccessDeniedException("权限不足，url不匹配");
            }

        }
        // 没匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
